import {
  reactive,
  onBeforeUnmount,
} from "vue";
import { designComponent } from "../../../src/use/designComponent";

interface Route {
  path?: string;
  hash?: string;
  param?: { [k: string]: string };
}

function getRoute(): Route {
  let locationHash = window.location.hash || "";
  if (locationHash.charAt(0) === "#") {
    locationHash = locationHash.slice(1);
  }
  const [path, hash] = decodeURIComponent(locationHash).split("#");
  return {
    path,
    hash,
  };
}

export const AppNavigator = designComponent({
  name: "AppNavigator",
  props: {
    defaultPath: String,
  },
  providerRefer: true,
  setup (props, setupContext) {
    const initRoute = getRoute();
    !initRoute.path && (initRoute.path = props.defaultPath);
  
    const state = reactive({route: initRoute});
    const methods = {
      go(path: string) {
        window.location.hash = encodeURIComponent(path);
      },
    };
    const handler = {
      hashchange: () => {state.route = getRoute();},
    };
    window.addEventListener("hashchange", handler.hashchange);
    onBeforeUnmount(() =>window.removeEventListener("hashchange", handler.hashchange));

    const refer = {
      state,
      methods,
    };
    return {
      refer,
      render: () => !!setupContext.slots.default ? setupContext.slots.default() : null
    }
  }
});
